<template>
  <section>

  </section>
</template>

<script>
  import util from "../../assets/js/util";
  import {userLoginByCodeUri} from "../../common/api";
  import Vue from 'vue';
  import {Toast} from 'vant';
  Vue.use(Toast);

  export default {
    data() {
      return {}
    },
    methods: {
      login(code) {
        const that = this;
        this.$http.get(userLoginByCodeUri + '?code=' + code).then(response => {
          let {code, msg, data} = response.body
          if (code != 0) {
            // Toast(msg);
            that.$router.replace({name: 'Home'})
          } else {
            window.localStorage.setItem('openid', data.user.openid);
            window.localStorage.setItem('access_token', data.user.access_token);
            window.localStorage.setItem('upload_token', data.user.upload_token);
            window.localStorage.setItem('user_id', data.user.id);
            that.GLOBAL.userInfo = data.user;
            that.GLOBAL.memberProfile = data.member;
            that.EventBus.$emit('OnUserLogined', null);

            window.sessionStorage.setItem('wx_auth', true);

            const referrer = localStorage.getItem('referrer');
            if(referrer) {
              that.$router.replace({path: referrer});
            } else {
              that.$router.replace({name: 'Home'})
            }
          }
        }, response => {
          // error callback
        })
      }
    },
    mounted: function () {
      //防止页面后退
      history.pushState(null, null, document.URL);
      window.addEventListener('popstate', function () {
        history.pushState(null, null, document.URL);
      });

      const code = util.getQueryVariable('code');
      if(code) {
        this.login(code);
      }
    }
  }
</script>

<style scoped>

</style>
